package com.lcq.demo.common.job;

import com.lcq.demo.entity.po.ScheduleTask;
import com.lcq.demo.repository.ScheduleTaskRepository;
import com.lcq.demo.service.ScheduleTaskLogService;
import com.lcq.demo.service.ScheduleTaskService;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ConditionalOnEnabledResourceChain;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
@DisallowConcurrentExecution
public class MyJob extends QuartzJobBean {

    @Autowired
    private ScheduleTaskLogService scheduleTaskLogService;

    @Resource
    private ScheduleTaskRepository scheduleTaskRepository;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        // 获取任务ID
        Integer taskId = (Integer) context.getMergedJobDataMap().get("taskId");

        // 查询任务
        ScheduleTask task = scheduleTaskRepository.findById(taskId).orElseThrow(() -> new RuntimeException("Task not found"));

        // 执行任务逻辑
        try {
            // 这里可以放置具体的任务逻辑
            System.out.println("Executing task: " + task.getTaskName());

            // 假设任务成功执行
            Integer executionStatus = 1;
            Date startTime = new Date();
            Thread.sleep(5000); // 模拟任务执行时间
            Date endTime = new Date();

            // 记录日志
            scheduleTaskLogService.logTaskExecution(task, executionStatus, startTime, endTime);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new JobExecutionException("Task interrupted");
        } catch (Exception e) {
            throw new JobExecutionException("Task failed");
        }
    }
}
